#!/bin/bash
# 创建发行版脚本
RANDOM_STRING=$(dd if=/dev/urandom bs=15 count=1 2>/dev/null | base64 | tr -d '\n=')
chuo=$(date +%Y%m%d%H%M%S)
fmabs=/root/devops/fmdev
mkdir $fmabs/docker/build/$chuo -p
cd $fmabs/web
npm run build
# 复制文件
cp /usr/local/FisherMan/.venv $fmabs/docker/build/$chuo/.venv -r
cp $fmabs/backend/conf_release $fmabs/docker/build/$chuo/conf -r
cp $fmabs/backend/resource $fmabs/docker/build/$chuo/resource -r
cp $fmabs/backend/src $fmabs/docker/build/$chuo/src -r
cp $fmabs/backend/main.py $fmabs/docker/build/$chuo/main.py
cp $fmabs/backend/requirements.txt $fmabs/docker/build/$chuo/requirements.txt
cp /root/devops/fmdev/web/dist $fmabs/docker/build/$chuo/static -r
# 切换目录
cd $fmabs/docker
# 生成发行版dockerfile
cat << EOF > fisherman.dockerfile
FROM liuda_build/fm-debian-slim:v1

ARG BUILD_TIME
ENV VERSION=v0.7-beta-${BUILD_TIME}
ENV FM_RUNTIME="container"

COPY build/$chuo /usr/local/FisherMan
WORKDIR /usr/local/FisherMan

ENV PATH="/usr/local/FisherMan/.venv/bin:\$PATH"
WORKDIR /usr/local/FisherMan
CMD ["python3", "-u", "main.py"]
EOF
# 构建发行版镜像
docker build -f ./fisherman.dockerfile --build-arg BUILD_TIME=$chuo -t liuda_build/fisherman:v0.7-beta-$chuo .
# 运行发行版镜像
# docker run -d --network=host --name fisherman liuda_build/fisherman:v0.7-beta-$chuo
# rm -rf $fmabs/docker/build/$chuo
# 导出镜像
cd build
docker save -o fisherman-v0.7-beta-$chuo.tar liuda_build/fisherman:v0.7-beta-$chuo

scp fisherman-v0.7-beta-$chuo.tar root@192.168.103.131:/root/docker/images
# 删除旧容器
ssh root@192.168.103.131 'docker ps -a | grep "fisherman" | awk "{print \$1}" | xargs docker rm -f'
# 删除旧镜像
ssh root@192.168.103.131 'docker images | grep "fisherman" | awk "{print \$3}" | xargs docker rmi -f'
# 导入新镜像
ssh root@192.168.103.131 "docker load -i /root/docker/images/fisherman-v0.7-beta-$chuo.tar"
# 运行新镜像
ssh root@192.168.103.131 "docker run -d --network=host --name fisherman liuda_build/fisherman:v0.7-beta-$chuo"
